from fastapi import APIRouter, Request, HTTPException
from loguru import logger
from app.services import service_manager
from app.utils.logger import log_exception

router = APIRouter()

@router.post("/dahua/callback")
@log_exception
async def dahua_callback(request: Request):
    """处理大华平台推送的事件"""
    try:
        event_data = await request.json()
        event_type = event_data.get("eventType")
        
        if event_type == "AccessControl":
            # 处理门禁事件
            await service_manager.process_card_event(event_data)
        elif event_type == "Face":
            # 处理人脸识别事件
            await service_manager.process_face_event(event_data)
        elif event_type == "Alarm":
            # 处理报警事件
            door_id = event_data.get("doorId")
            if door_id:
                await service_manager.alarm_service.trigger_force_open_alarm(door_id)
                
        logger.info(f"处理大华平台事件: {event_type}")
        return {"message": "事件处理成功", "status": "success"}
        
    except Exception as e:
        logger.error(f"处理大华平台事件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/hikvision/callback")
@log_exception
async def hikvision_callback(request: Request):
    """处理海康平台推送的事件"""
    try:
        event_data = await request.json()
        event_type = event_data.get("eventType")
        
        if event_type == "FACE_MATCH":
            # 处理人脸识别事件
            await service_manager.process_face_event(event_data)
        elif event_type == "ACCESS_CONTROL":
            # 处理门禁事件
            await service_manager.process_card_event(event_data)
        elif event_type == "ALARM":
            # 处理报警事件
            door_id = event_data.get("doorIndexCode")
            if door_id:
                await service_manager.alarm_service.trigger_force_open_alarm(door_id)
                
        logger.info(f"处理海康平台事件: {event_type}")
        return {"message": "事件处理成功", "status": "success"}
        
    except Exception as e:
        logger.error(f"处理海康平台事件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e)) 